<template>
  <div id="div-body">
    <div id="divbox">
      <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="" prop="householdNames">
            <el-input
              v-model="queryParams.completeAddress"
              placeholder="输入关键字"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-popover
              placement="buttom"
              width="450"
              trigger="click">
              <!--<el-table :data="gridData"  height="650"   border  >
                <el-table-column width="400" property="completeAddress" @row-click="addressClick"  label="搜索结果" ></el-table-column>
              </el-table>-->
              <el-table
                :data="gridData"
                height="650"
                border
                @row-click="addressClick"
                style="width: 100%">
                <el-table-column
                  prop="completeAddress"
                  label="搜索结果"
                  width="400">
                </el-table-column>
              </el-table>
              <el-button slot="reference" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            </el-popover>
            &nbsp;
            <el-button type="primary"  size="mini" @click="selectAll">全部</el-button>
            <el-button type="primary"  size="mini" @click="insertPoint">新增</el-button>
            <el-button type="primary"  size="mini" @click="eliminate">清除</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div id="fontbox">
        <span>选择标识属性</span>
        <el-divider></el-divider>
        <el-checkbox-group v-model="checkList">
          <el-checkbox label="街路巷"></el-checkbox>
          <el-checkbox label="门牌号"></el-checkbox>
          <el-checkbox label="户主姓名"></el-checkbox>
        </el-checkbox-group>
      </div>
      <el-divider></el-divider>
      <div id="fonboxtwo"  style="height:300px;overflow-y:auto">
        <span>选择街路巷(村)</span>
        <el-divider></el-divider>
        <el-tree
          :data="deptOptions"
          show-checkbox
          node-key="id"
          :default-expanded-keys="['441802105003','441802105002','441802105001','441803102003000','441803102202000']"
          :props="defaultProps"
          @check-change="handleCheckChange"
        >

        </el-tree>

      </div>
      <el-divider></el-divider>
    </div>
    <div id="map" class="map" ></div>
    <div id="popup"  style="width: 450px"
         class="ol-popup">
      <a href="#"
         id="popup-closer"
         class="ol-popup-closer"></a>
      <div id="popup-content" > </div>
    </div>
  </div>
</template>

<script>
  import { treeselect,getAddressIndex, selectAll, treeResponse} from "@/api/address/userAddress";
  import "ol/ol.css";
  import { get as getProjection } from "ol/proj";
  import { getWidth, getTopLeft } from "ol/extent";
  import View from "ol/View";
  import Map from "ol/Map";
  import TileLayer from "ol/layer/Tile";
  import WMTS from "ol/source/WMTS";
  import WMTSTileGrid from "ol/tilegrid/WMTS";
  import VectorSource from "ol/source/Vector";
  import VectorLayer from "ol/layer/Vector";
  import Feature from 'ol/Feature';
  import Point from 'ol/geom/Point';
  import {Circle as CircleStyle, Fill,Text, Style,Stroke} from 'ol/style';
  import Overlay from 'ol/Overlay';
  import Draw from 'ol/interaction/Draw';
  import popupC from './popup';
  import Vue from 'vue';
  import insertpop from './insertPoint';
  import {fromLonLat} from 'ol/proj';



  export default {
    name: "UserAddress",
    inject: ['reload'],
    data() {
      return {
        //弹出框
        gridData: [{
          completeAddress: null
        }],
        //地图容器
        map: null,
        view: null,
        vectorSource: null,
        makerLayer:null,
        iconStyle: null,
        iconFeature:null,
        container :null,
        content :null,
        popupCloser :null,
        overlay :null,
        draw: null,
        drawSource: null,
        drawLayer:null,
        //tree组件
        deptOptions:undefined,
        defaultProps: {
          children: 'children',
          label: 'leader'
        },

        //多选框
        checkList: ['街路巷','门牌号'],
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 地址查看表格数据
        userAddressList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          ybssProvince: null,
          ybssCity: null,
          ybssCounty: null,
          ybssStreet: null,
          belongingCommunity: null,
          policeStation: null,
          policeRoom: null,
          levelCode: null,
          municipalCode: null,
          districtCode: null,
          theCode: null,
          communityCode: null,
          stationCode: null,
          policeOfficeCode: null,
          streetRoadLan: null,
          houseNumber: null,
          housingEstate: null,
          childStreet: null,
          sonHouseNumber: null,
          subDistrict: null,
          thirdRoadLane: null,
          gradeNumber: null,
          levelNeighborhood: null,
          nameofBuildings: null,
          nameofTheunit: null,
          nameofTheroom: null,
          completeAddress: null,
          imagePath: null,
          x: null,
          y: null,
          addPersonName: null,
          addTime: null,
          modificationTime: null,
          modifierName: null,
          ybssState: null,
          householdNames: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        //滚动条
        count:0,
      };
    },
    mounted() {
      this.initMap()
    },
    created() {
      this.getBelongingCommunity();

    },
    methods: {

      //加载地图
      initMap() {
        var this_ = this;
        // 渲染地图
        var projection = getProjection('EPSG:4326')
        var projectionExtent = projection.getExtent()
        var size = getWidth(projectionExtent) / 256
        var resolutions = new Array(18)

        var matrixIds = new Array(18)
        for (var z = 1; z < 19; ++z) {
          resolutions[z] = size / Math.pow(2, z)
          matrixIds[z] = z
        }
        var webKey = '859abc244331a2b8b9a056908a12e4ed'
        var wmtsUrl_1 = 'http://t0.tianditu.gov.cn/img_c/wmts?tk='

        this.view = new View({
          center: [113.0674836784, 23.602077],
          projection: projection,
          zoom: 18
        })
         this.map = new Map({
          layers: [
            new TileLayer({
              opacity: 0.7,
              source: new WMTS({
                url: wmtsUrl_1 + webKey,
                layer: 'img',
                matrixSet: 'c',
                format: 'tiles',
                style: 'default',
                projection: projection,
                tileGrid: new WMTSTileGrid({
                  origin: getTopLeft(projectionExtent),
                  resolutions: resolutions,
                  matrixIds: matrixIds
                }),
                wrapX: true
              })
            }),
          ],
          target: 'map',
          view: this.view
        })

        this.vectorSource = new VectorSource()
        this.makerLayer = new VectorLayer({
          source: this.vectorSource
        })
        this.map.addLayer(this.makerLayer)
        this.drawSource = new VectorSource()
        this.drawLayer = new VectorLayer({
          source:this.drawSource
        })
        this.map.addLayer(this.drawLayer)
        //弹窗容器
        var container  = document.getElementById('popup');
        var content = document.getElementById('popup-content')
        var popupCloser = document.getElementById('popup-closer')
        var overlay = new Overlay({
          element:container,
          autoPan:true
        })

        this.map.addOverlay(overlay)

        //地图点击
        this.map.on("click",function (e) {
          var pixel = this_.map.getEventPixel(e.originalEvent)
          this_.map.forEachFeatureAtPixel(pixel,function(feature){
            if(feature.values_.properties !=undefined){
              var ybssid = feature.values_.properties
              const coordinate = e.coordinate;
              content.innerHTML = '<div class="detail" ></div>'
              var mat = new Vue({
                render: h =>
                  h(popupC, {
                    props: {
                      ybssid
                    }
                  })
              }).$mount('.detail')

              overlay.setPosition(coordinate);
              //关闭弹窗
              popupCloser.onclick = function () {
                overlay.setPosition(undefined);
                popupCloser.blur();
                mat.$destroy();
                return false;
              };
            }
          });

        })
      },




      //查询社区下拉列表
      getBelongingCommunity() {
        treeselect().then(response => {
         this.deptOptions=response.data
        }).catch(err => console.log(err));
      },



      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },


     //搜索按钮
      handleQuery() {
        var completeAddress = this.queryParams.completeAddress;
        this.queryParams.pageNum = 1;
        this.getAddressIndex(completeAddress);
      },



      //模糊查询
      getAddressIndex(completeAddress){
        getAddressIndex(completeAddress).then(response => {
          this.gridData=response.data
          this.addPoints(response)
        }).catch(err => console.log(err));
      },


      //模糊查询弹窗行点击事件
      addressClick(row){
        let that = this;
        that.view.setCenter([row.x,row.y])
      },


      //添加坐标点
      addPoints(response){
        for(var i = 0 ; i<response.data.length;i++){
           var item = response.data[i]
           var x = item.x
           var y = item.y
           var houseNumber = item.houseNumber

          const iconFeature = new Feature({
            geometry: new Point([x, y]),
            properties:item
          });
          iconFeature.setStyle(new Style({
            image: new CircleStyle({
              radius: 5,
              fill: new Fill({
                color: 'red',
              }),
            }),
            text: new Text({
              font: '14px Calibri,sans-serif',
              text: houseNumber,
              textAlign:'left',
              fill: new Fill({
                color: '#f72304'
              })
            })
          }));
            this.makerLayer.getSource().addFeature(iconFeature)
          }
      },


      //新增
      insertPoint(){
        if(!this.draw){
          this.draw = new Draw({
            source: this.drawSource,
            type: 'Point',
            style: new Style({
              fill: new Fill({
                color: 'yellow'
              }),
              stroke: new Stroke({
                color: '#ffcc33',
                width: 2
              }),
              image: new CircleStyle({
                radius: 7,
                fill: new Fill({
                  color: '#ffcc33'
                })
              })
            })
          });
          this.map.addInteraction(this.draw);
        }
        var that = this
        var container  = document.getElementById('popup');
        var content = document.getElementById('popup-content')
        var popupCloser = document.getElementById('popup-closer')
        var overlay = new Overlay({
          element: container,
          autoPan: true
        })
        that.map.addOverlay(overlay)
        this.draw.on('drawend', function(event){
          // event.feature 就是当前绘制完成的线的Feature
          var xy = event.feature.getGeometry().getCoordinates();
          var x = xy[0]
          var y = xy[1]
          content.innerHTML = '<div id="pop" ></div>'
          var want = new Vue({
            render: h =>
              h(insertpop, {
                props: {
                  x,
                  y,
                }
              })
          }).$mount('#pop')
          popupCloser.onclick = function () {
            overlay.setPosition(undefined);
            popupCloser.blur();
            want.$destroy();
            return false;
          };
          overlay.setPosition(xy);
        })
      },


      //全部
      selectAll(){
        selectAll().then(response =>{
        this.addPoints(response)
        }).catch(err =>console.log(err));
      },


      //节点查询
      handleCheckChange(node,data){
        treeResponse(node.id).then(response =>{
          if(data == true){
            this.addPoints(response)
          }else if(data == false){
            this.removePoints(node.id)
          }
        }).catch(err =>console.log(err))
      },


      //移除点要素
     removePoints(id){
        let that = this
         that.makerLayer.getSource().getFeatures().forEach(function (feature) {
           var code=feature.values_.properties.communityCode+'_'+feature.values_.properties.ybssId
           if(code == id) {
             that.makerLayer.getSource().removeFeature(feature);

           }
        })
     },

      //清除所有
      eliminate(){
        let that = this
        that.makerLayer.getSource().getFeatures().forEach(function (feature) {
          that.makerLayer.getSource().removeFeature(feature);
        })
      },
    }
  };
</script>
<style>

  #divbox{
    width:550px;
  }
  #map{
    width: 1150px;
    height: 850px;
    position: absolute;
    top: 5px;
    left: 550px;
  }
  .ol-popup {
    position: absolute;
    background-color: white;
    box-shadow: 0 1px 4px rgba(0,0,0,0.2);
    padding: 15px;
    border-radius: 10px;
    border: 1px solid #cccccc;
    bottom: 12px;
    left: -50px;
    min-width: 280px;
  }
  .ol-popup:after, .ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
  }
  .ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 48px;
    margin-left: -10px;
  }
  .ol-popup:before {
    border-top-color: #cccccc;
    border-width: 11px;
    left: 48px;
    margin-left: -11px;
  }
  .ol-popup-closer {
    text-decoration: none;
    position: absolute;
    top: 2px;
    right: 8px;
  }
  .ol-popup-closer:after {
    content: "✖";

  }


</style>
